package com.pokermadness.servlets;

import java.io.IOException;
//import java.util.HashMap;

//import javax.servlet.ServletContext;
import javax.servlet.ServletException;
//import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.json.JSONException;

import com.pokermadness.game.Game;

public class GameServlet extends HttpServlet {

	public void init() {
		System.out.println("init called");
//		ServletContext context = getServletContext();
//		if (context.getAttribute("active-sessions") == null)
//			context.setAttribute("active-sessions",
//					new HashMap<String, HttpSession>());
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		HttpSession session;
//		@SuppressWarnings("unchecked")
//		HashMap<String, HttpSession> map = (HashMap<String, HttpSession>) getServletContext()
//				.getAttribute("active-sessions");
//		String key = getCookieValue(request.getCookies(), "session", "-1");
//		if (map.containsKey(key)) {
//			session = map.get(key);
//		} else {
			session = request.getSession(true);
			session.setMaxInactiveInterval(3600);
//		}
		Game game = (Game) session.getAttribute("game");
		if (game == null) {
			game = new Game();
			game.startGame();
			session.setAttribute("game", game);
		}
		System.out.println("Session id is: " + session.getId() + ", game id is: " + game.toString() + ", servlet id is: " + this.toString());
//		Cookie cookie = new Cookie("session", session.getId());
//		cookie.setMaxAge(3600);
//		cookie.setPath(request.getContextPath());
//		response.addCookie(cookie);
		response.setContentType("application/json");
		if (request.getParameterMap().containsKey("initGame")) {
			postGetInitGame(request, response, game);
			session.removeAttribute("game");
			session.setAttribute("game", game);
		} else if (request.getParameterMap().containsKey("move")) {
			processPlayerMove(request, response, game);
			session.removeAttribute("game");
			session.setAttribute("game", game);
		} else if (request.getParameterMap().containsKey("send")) {
			sendMove(request, response, game);
			session.removeAttribute("game");
			session.setAttribute("game", game);
		} else if (request.getParameterMap().containsKey("finish")) {
			finishGame(request, response, game);
			session.removeAttribute("game");
			session.setAttribute("game", game);
		} else if (request.getParameterMap().containsKey("end")) {
			endGame(session);
		} else if (request.getParameterMap().containsKey("isRunning")) {
			isRunning(request, response, game);
		} else if (request.getParameterMap().containsKey("initSession")) {
			response.getWriter().write("");
		}
	}

	private void postGetInitGame(HttpServletRequest request,
			HttpServletResponse response, Game game) throws IOException {
		boolean addLog;
		if (request.getParameter("sendLog").equals("true"))
			addLog = true;
		else
			addLog = false;
		response.getWriter().write(game.getInitString(addLog));
	}

	private void isRunning(HttpServletRequest request,
			HttpServletResponse response, Game game) throws IOException {
		response.getWriter().write(game.getIsRunningString());
	}

	private void processPlayerMove(HttpServletRequest request,
			HttpServletResponse response, Game game) throws IOException {
		int move = Integer.parseInt(request.getParameter("move"));
		response.getWriter().write(game.makeMove(move));
	}

	private void sendMove(HttpServletRequest request,
			HttpServletResponse response, Game game) throws IOException {
		try {
			response.getWriter().write(game.playRound().toString());
		} catch (JSONException e) {
			e.printStackTrace();
		}
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e1) {
			e1.printStackTrace();
		}
	}

	private void finishGame(HttpServletRequest request,
			HttpServletResponse response, Game game) throws IOException {
		response.getWriter().write(game.finishGame());
	}

	private void endGame(HttpSession session) {
		session.removeAttribute("game");
	}

//	private String getCookieValue(Cookie[] cookies, String cookieName,
//			String defaultValue) {
//		if (cookies == null)
//			return defaultValue;
//		for (int i = 0; i < cookies.length; i++) {
//			Cookie cookie = cookies[i];
//			if (cookieName.equals(cookie.getName()))
//				return (cookie.getValue());
//		}
//		return (defaultValue);
//	}

}
